
/**    
 *   This file is part of the FSKModem java/android library for 
 *   processing FSK audio signals. 
 *   
 *   The FSKModem library is developed by Ivan Ganev, CEO at
 *   Cytec BG Ltd.
 *
 *   Copyright (C) 2014  Cytec BG Ltd. office@cytec.bg
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package bg.cytec.android.fskmodem;

import java.io.IOException;
import java.nio.ShortBuffer;

import android.app.Activity;
import android.content.Intent;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import bg.cytec.android.fskmodem.FSKDecoder.FSKDecoderCallback;
import bg.cytec.android.fskmodem.FSKEncoder3.FSKEncoderCallback;

public class EncodeLive8bitActivity extends Activity {

	public static final String ENCODER_DATA = "Hello World! This text has been encoded realtime and then fed to audio playback stream and the FSK decoder that actually displays it.";
	
	protected FSKConfig mConfig;
	protected FSKEncoder3 mEncoder;
	protected FSKDecoder mDecoder;
	
	protected AudioTrack mAudioTrack;
	
	private short[] data = null;
	
	private EditText editText;
	
    public int pwMinBufferSize = 0;
	
	protected Runnable mDataFeeder = new Runnable() {
		
		@Override
		public void run() {
//			byte[] data = ENCODER_DATA.getBytes();
			
			if (data.length > FSKConfig.ENCODER_DATA_BUFFER_SIZE) {
				//chunk data
				short[] buffer = new short[FSKConfig.ENCODER_DATA_BUFFER_SIZE];
				ShortBuffer dataFeed = ShortBuffer.wrap(data);
				while (dataFeed.remaining() > 0) {
					
					if (dataFeed.remaining() < buffer.length) {
						buffer = new short[dataFeed.remaining()];
					}
					
					dataFeed.get(buffer);
					mEncoder.appendData(buffer);
					try {
						Thread.sleep(100); //wait for encoder to do its job, to avoid buffer overflow and data rejection
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
			else {
				mEncoder.appendData(data);
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_bak);
		editText = (EditText)findViewById(R.id.fsmText);
		
		
		/// INIT FSK CONFIG
		
		try {
			pwMinBufferSize = AudioTrack.getMinBufferSize(FSKConfig.SAMPLE_RATE_44100,  AudioFormat.CHANNEL_OUT_STEREO,   AudioFormat.ENCODING_PCM_8BIT);
			mConfig = new FSKConfig(FSKConfig.SAMPLE_RATE_44100, FSKConfig.PCM_8BIT, FSKConfig.CHANNELS_STEREO, FSKConfig.SOFT_MODEM_MODE_6, FSKConfig.THRESHOLD_20P);
		} catch (IOException e1) {
			e1.printStackTrace();
		}

	/*	/// INIT FSK DECODER
		
		mDecoder = new FSKDecoder(mConfig, new FSKDecoderCallback() {
			
			@Override
			public void decoded(byte[] newData) {
				
				final String text = new String(newData);
				
				runOnUiThread(new Runnable() {
					public void run() {
						
						TextView view = ((TextView) findViewById(R.id.result));
						
						view.setText(view.getText()+text);
					}
				});
			}
		});*/
		
		/// INIT FSK ENCODER
		
		mEncoder = new FSKEncoder3(mConfig, new FSKEncoderCallback() {
			@Override
			public void encoded(byte[] pcm8, short[] pcm16) {
				if (mConfig.pcmFormat == FSKConfig.PCM_8BIT) {
					//8bit buffer is populated, 16bit buffer is null
					//mAudioTrack.write(pcm8, 0, pcm8.length);
						//mDecoder.appendSignal(pcm8);
					mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,mConfig.sampleRate, AudioFormat.CHANNEL_OUT_STEREO,AudioFormat.ENCODING_PCM_8BIT, pcm8.length,AudioTrack.MODE_STATIC);
					mAudioTrack.write(pcm8, 0, pcm8.length);
					mAudioTrack.play();//开始播放
					try {
						int durtion = (int)((pcm8.length) * ( 1000  /(float)mConfig.sampleRate ) +10) ;
						Thread.sleep(durtion);
						mAudioTrack.release();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				else if (mConfig.pcmFormat == FSKConfig.PCM_16BIT) {
					//16bit buffer is populated, 8bit buffer is null
					
					mAudioTrack.write(pcm16, 0, pcm16.length);
					
					mDecoder.appendSignal(pcm16);
				}
			}
		});
		
		///
		
		mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
				mConfig.sampleRate, AudioFormat.CHANNEL_OUT_STEREO,
				AudioFormat.ENCODING_PCM_8BIT, 1024,
				AudioTrack.MODE_STATIC);
//		mAudioTrack.play();
		///
	}
	
	@Override
	protected void onDestroy() {
		mDecoder.stop();
		
		mEncoder.stop();
		
		mAudioTrack.stop();
		mAudioTrack.release();
		
		super.onDestroy();
	}

	
	public void onClick(View view){
		switch (view.getId()) {
		case R.id.play:
			String cmds = editText.getText().toString();
			data =  String2Int(cmds);
			new Thread(mDataFeeder).start();
			break;
		case R.id.sendFrey:
			Intent intent = new Intent(this,EncodeLive8bitFreyActivity.class);
			startActivity(intent);
		default:
			break;
		}
	}
	
	public static short[] String2Int(String _s) {
		String s[] = _s.split(",");
		int iLen = s.length;
		short aCMD[] = new short[iLen];
		for (int i = 0; i < s.length; i++) {
			aCMD[i] = CInt(s[i], (short)0);
		}
		return aCMD;
	}
	
	/*
	 * 字符串转为整数 str 源字符串, default 默认值
	 */
	public static short CInt(String str, short iDefault) {
		short iR = iDefault;
		try {
			iR = Short.parseShort(str);
		} catch (NumberFormatException e) {
			iR = iDefault;
		}
		return iR;
	}
	
}

